﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DIS.Infrastructure.Entities.Entity;
using DIS.Portal.Biz;
using DIS.Tool.Framework;
using System.Collections;
using DIS.Infrastructure.Entities.DTO;
using System.Text;
using DIS.Infrastructure.Entities;
using System.Data.SqlClient;
using System.Data;
using DIS.Portal.WebLogic;
using DIS.Infrastructure.Entities.Enum;

namespace IDS.Portal.Web.Controllers
{
     [Auth]
    public class ReimbursementController : Controller
    {
        //
        // GET: /Reimbursement/

        public ActionResult Index()
        {
            return View();
        }

        #region 市内交通费
        public ActionResult CityTaxiFee(int page = 0)
        {
            ViewBag.feelist = CityTaxiFeeBiz.GetAllCityTaxiFee(page, 20);
            return View();
        }

        public ActionResult CityTaxiFeeDetail(int Id = 0)
        {
            var yearmonth = new FinancialPeriod().FindAll();
            ViewBag.YearMonth = yearmonth;
            var user = new User().Find(c => c.UserName == System.Web.HttpContext.Current.User.Identity.Name);
            ViewBag.User = user;
            ViewBag.projects = new Project().FindAll();
            if (Id > 0)
            {
                using (Context ctx = new Context())
                {
                    var data = (from c in ctx.CityTaxi
                                join d in ctx.Project
                                on c.ProjectId equals d.Id
                                where c.Id == Id
                                select new { c, d })
                              .ToList()
                              .Select(e => new CityTaxi().Set(e.c).LoadProject(e.d)).FirstOrDefault();
                    var cityTaxi = data;
                    ViewBag.cityTaxi = cityTaxi;
                }
               
                var cityTaxiDetails = new CityTaxiDetail().FindAll(c => c.CityTaxiId == Id);
               
                ViewBag.cityTaxiDetails = cityTaxiDetails;
            }
            return View();
        }

        [HttpPost]
        public ActionResult SaveCityTaxiFee(string[] reconnaissancedate, string[] businessaddress,
            string[] reconnaissancename, string[] taxfee, string[] invoicecount, string selyearmonth, int state = 0, int MainId = 0,int projectId=0)
        {

            if (reconnaissancedate != null && reconnaissancedate.Length > 0)
            {

                var fee = new CityTaxi();
                var feedetailList = new List<CityTaxiDetail>();
                decimal totalfee = 0;
                int count = 0;
                for (int i = 0; i < reconnaissancedate.Length; i++)
                {
                    if (reconnaissancedate[i] != "")
                    {
                        var detail = new CityTaxiDetail();
                        detail.ReconnaissanceDate = reconnaissancedate[i];
                        var counttemp = invoicecount[i] == "" ? 0 : int.Parse(invoicecount[i]);
                        count = count + counttemp;
                        detail.InvoiceCount = counttemp;
                        detail.ReconnaissanceName = reconnaissancename[i];
                        var totalfeeTemp = taxfee[i] == "" ? 0 : decimal.Parse(taxfee[i]);
                        totalfee = totalfee + totalfeeTemp;
                        detail.TaxiFee = totalfeeTemp;
                        detail.TravelAddress = businessaddress[i];
                        feedetailList.Add(detail);
                    }
                }
                if (selyearmonth != null && selyearmonth != "无")
                {
                    string[] temp = selyearmonth.Split('$')[0].Split(':');
                    fee.EndDate = temp[3];
                    fee.Month = temp[1];
                    fee.StartDate = temp[2];
                    fee.Year = temp[0];
                }
                fee.Id = MainId;
                fee.ProjectId = projectId;
                fee.InvoiceCount = count;
                fee.Status = state;
                fee.TaxiFee = totalfee;
                fee.UserName = System.Web.HttpContext.Current.User.Identity.Name;


                if (MainId > 0)
                {
                    var details = new CityTaxiDetail().FindAll(c => c.CityTaxiId == MainId);
                    foreach (var item in details)
                    {
                        var tempItem = new CityTaxiDetail().Find(item.Id.ToString());
                        tempItem.PostDelete();
                    }
                }

                CityTaxiFeeBiz.SaveCityTaxiFee(fee, feedetailList);

            }

            return Redirect("/Reimbursement/CityTaxiFee");
        }

        public ActionResult ChangeState(int page = 0, int Id = 0, int state = 0)
        {
            if (state == -1)//删除
            {
                var taxifee = new CityTaxi().Find(Id.ToString());
                taxifee.PostDelete();
                var details = new CityTaxiDetail().FindAll(c => c.CityTaxiId == Id);
                foreach (var item in details)
                {
                    var tempItem = new CityTaxiDetail().Find(item.Id.ToString());
                    tempItem.PostDelete();
                }
            }
            else
            {
                var taxifee = new CityTaxi().Find(Id.ToString());
                taxifee.Status = state;
                taxifee.PostModify();
            }
            return Redirect("/Reimbursement/CityTaxiFee?page=" + page);
        }
        #endregion
        #region 在途费用(长途车费)
        public ActionResult LongHaulFee(int page = 0)
        {
            if (System.Web.HttpContext.Current.Request.Cookies["LongHaulDetail"] == null)
            {
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["LongHaulDetail"];
                oCookie.Expires = DateTime.Now.AddHours(-1);
            }
            ViewBag.feelist = LongHaulBiz.GetAllLongHaulFee(page, 20);
            return View();
        }

        public ActionResult LongHaulFeeDetail(int Id = 0)
        {
            var yearmonth = new FinancialPeriod().FindAll();
            ViewBag.YearMonth = yearmonth;
            var user = new User().Find(c => c.UserName == System.Web.HttpContext.Current.User.Identity.Name);
            ViewBag.User = user;
            ViewBag.projects = new Project().FindAll();
            if (Id > 0)
            {
                using (Context ctx = new Context())
                {
                    var data = (from c in ctx.LongHaul
                                join d in ctx.Project
                                on c.ProjectId equals d.Id
                                where c.Id == Id
                                select new { c, d })
                              .ToList()
                              .Select(e => new LongHaul().Set(e.c).LoadProject(e.d)).FirstOrDefault();
                    var longHaul = data;
                    ViewBag.longHaul = longHaul;
                }
               // var longHaul = new LongHaul().Find(Id.ToString());
                var longHaulDetails = new LongHaulDetail().FindAll(c => c.LongHaulId == Id);
                string tbody = GetTboby(longHaulDetails);
               // ViewBag.longHaul = longHaul;
                ViewBag.longHaulDetails = longHaulDetails;
                ViewBag.tbody = tbody;
                 
            }
            ViewBag.Id = Id;
            return View();
        }

        public string GetTboby(List<LongHaulDetail> detailList)
        {
            StringBuilder sb = new StringBuilder();

            if (detailList != null && detailList.Count > 0)
            {
                var tempList = new List<LongHaulDetail>();
                int j=1;
                foreach (var item in detailList)
                {
                    var temp = item;
                    string[] des = item.LongHaulDescription.Split('#');
                    var longdtoList = new List<LongHaulDTO>();
                    foreach (var str in des)
                    {
                        if (str != "")
                        {
                            var dto = new LongHaulDTO();
                            var dtos = str.Split('|');

                            dto.BusDate = dtos[2];
                            dto.EndAddress = dtos[1];
                            dto.Fee =decimal.Parse(dtos[4] == "" ? "0" : dtos[4]);
                            dto.InvoiceCount = int.Parse(dtos[5] == "" ? "0" : dtos[5]);
                            dto.StartAddress = dtos[0];
                            dto.Transport = dtos[3];
                            longdtoList.Add(dto);
                        }
                    }
                    temp.tempId = j;
                    temp.dtoList = longdtoList;
                    tempList.Add(temp);
                    j++;
                }
                HttpCookie oCookie = new HttpCookie("LongHaulDetail");

                oCookie.Expires = DateTime.Now.AddHours(1);
                oCookie.Value = tempList.ToJson();

                System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);
                sb.Append(ConvertToStr(tempList).Split('^')[0]);
            }

            return sb.ToString();
        }

        [HttpPost]
        public ActionResult AddInfo(string start, string end, string busdate, string transport, string fee, string invoice)
        {

            LongHaulDetail detail = null;
            List<LongHaulDetail> detailList = null;
            if (start != null && start.Length > 0)
            {
                start = start.Substring(0, start.Length - 1);
                var starts = start.Split(',');
                end = end.Substring(0, end.Length - 1);
                var ends = end.Split(',');
                busdate = busdate.Substring(0, busdate.Length - 1);
                var busdates = busdate.Split(',');
                transport = transport.Substring(0, transport.Length - 1);
                var transports = transport.Split(',');
                fee = fee.Substring(0, fee.Length - 1);
                var fees = fee.Split(',');
                invoice = invoice.Substring(0, invoice.Length - 1);
                var invoices = invoice.Split(',');

                ArrayList list = new ArrayList(busdates);
                list.Sort();
                string minDate = list[0].ToString();
                string maxDate = list[list.Count - 1].ToString();
                int days = 0;
                try
                {
                    days = (Convert.ToDateTime(maxDate) - Convert.ToDateTime(minDate)).Days;
                }
                catch (Exception ex)
                {
                }



                var dtolist = new List<LongHaulDTO>();
                string discription = "";
                int invoiceCount = 0;
                decimal feeCount = 0;
                for (int i = 0; i < starts.Length; i++)
                {
                    var dto = new LongHaulDTO();
                    dto.BusDate = busdates[i];
                    dto.EndAddress = ends[i];
                    dto.Fee = decimal.Parse(fees[i].ToString() == "" ? "0" : fees[i].ToString());
                    dto.InvoiceCount = int.Parse(invoices[i].ToString() == "" ? "0" : invoices[i].ToString());
                    dto.StartAddress = starts[i];
                    dto.Transport = transports[i];

                    dtolist.Add(dto);


                    feeCount = feeCount + decimal.Parse(fees[i].ToString() == "" ? "0" : fees[i].ToString());
                    invoiceCount = invoiceCount + int.Parse(invoices[i].ToString() == "" ? "0" : invoices[i].ToString());
                    string tempStr = starts[i] + "|" + ends[i] + "|" + busdates[i] + "|" + transports[i] + "|" + (fees[i].ToString() == "" ? "0" : fees[i].ToString()) + "|" + (invoices[i].ToString() == "" ? "0" : invoices[i].ToString());
                    discription = discription + tempStr + "#";

                }
                detail = new LongHaulDetail();
                detail.TotalFee = feeCount;
                detail.LongHaulDescription = discription == "" ? "" : discription.Substring(0, discription.Length - 1);
                detail.InvoiceCount = invoiceCount;
                detail.Days = days+1;
                detail.AllowanceMoney = (days + 1) * SupportBiz.GetAllowanceMoney();
                detail.dtoList = dtolist;
                //detailList.Add(detail);
            }
            if (System.Web.HttpContext.Current.Request.Cookies["LongHaulDetail"] == null)
            {
                if (detail != null)
                {
                    detailList = new List<LongHaulDetail>();
                    detail.tempId = 1;
                    detailList.Add(detail);

                    HttpCookie oCookie = new HttpCookie("LongHaulDetail");

                    oCookie.Expires = DateTime.Now.AddHours(1);
                    oCookie.Value = HttpUtility.UrlEncode(detailList.ToJson(), Encoding.GetEncoding("UTF-8")); 

                    System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);
                }
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["LongHaulDetail"];

                string tempCart = System.Web.HttpUtility.UrlDecode(oCookie.Value, Encoding.GetEncoding("UTF-8")).ToString();
                var tempList = new List<LongHaulDetail>();
                tempList = TypePlug.ToObject<List<LongHaulDetail>>(tempCart);
                detailList = tempList;
                if (detail != null)
                {
                    if (tempList.Count > 0)
                    {
                        detail.tempId = tempList.Max(c => c.tempId) + 1;
                    }
                    else
                    {
                        detail.tempId = 1;
                    }
                    detailList.Add(detail);
                }
                oCookie.Value = HttpUtility.UrlEncode(detailList.ToJson(), Encoding.GetEncoding("UTF-8")); 
                oCookie.Expires = DateTime.Now.AddHours(1);
                System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);
            }
            return Content(ConvertToStr(detailList));
        }

        [HttpPost]
        public ActionResult RemoveInfo(int id)
        { 
            List<LongHaulDetail> detailList = null;
            if (System.Web.HttpContext.Current.Request.Cookies["LongHaulDetail"] == null)
            { 
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["LongHaulDetail"];
                oCookie.Expires = DateTime.Now.AddHours(1);
                string tempCart = System.Web.HttpUtility.UrlDecode(oCookie.Value, Encoding.GetEncoding("UTF-8")).ToString(); 
                var tempList = new List<LongHaulDetail>();
                tempList = TypePlug.ToObject<List<LongHaulDetail>>(tempCart);
                var item = tempList.Where(c => c.tempId == id).FirstOrDefault();
                tempList.Remove(item);
                if (tempList.Count == 0)
                {
                    oCookie.Expires = DateTime.Now.AddDays(-1);
                }
               
                    detailList = tempList;
                    oCookie.Value = HttpUtility.UrlEncode(detailList.ToJson(), Encoding.GetEncoding("UTF-8")); 
                    System.Web.HttpContext.Current.Response.Cookies.Add(oCookie);
               
            }
            return Content(ConvertToStr(detailList));
        }

        public string ConvertToStr(List<LongHaulDetail> detailList)
        {
            string userName = System.Web.HttpContext.Current.User.Identity.Name;
            string realName = new User().Find(c => c.UserName == userName).RealName;
            StringBuilder sb = new StringBuilder();
            int days = 0;
            decimal totalfee = 0;
            int totalinvoicecount = 0;
            if (detailList != null && detailList.Any())
            {

                foreach (var item in detailList)
                {
                    totalfee = totalfee + item.TotalFee;
                    days = days + item.Days;
                    totalinvoicecount = totalinvoicecount + item.InvoiceCount;
                    if (item.dtoList != null && item.dtoList.Count > 0)
                    {
                        int rowcount = item.dtoList.Count;
                        int j = 0;
                        foreach (var dto in item.dtoList)
                        {
                            if (j == 0)
                            {
                                sb.Append("<tr bgcolor=\"#FFFFFF\" align=\"center\">");
                                sb.Append("<td width=\"10%\" align=\"center\">" + realName + "<input type=\"hidden\" name=\"Id\" value=\"" + item.tempId + "\" /></td>");
                                sb.Append("<td width=\"15%\" align=\"center\">" + dto.StartAddress + "</td>");
                                sb.Append("<td width=\"15%\" align=\"center\">" + dto.EndAddress + "</td>");
                                sb.Append("<td width=\"15%\" align=\"center\">" + dto.BusDate + "</td>");
                                sb.Append("<td width=\"10%\" align=\"center\" rowspan=\"" + rowcount + "\">" + item.Days + "</td>");
                                sb.Append("<td width=\"10%\" align=\"center\">" + dto.Transport + "</td>");
                                sb.Append("<td width=\"10%\" align=\"center\">" + dto.Fee + "</td>");
                                sb.Append("<td width=\"10%\" align=\"center\">" + dto.InvoiceCount + "</td>");
                                sb.Append("<td width=\"5%\" align=\"center\"><button type=\"button\" onclick=\"removeInfo(" + item.tempId + ")\">[-]</button></td>");
                                sb.Append("</tr>");
                            }
                            else
                            {
                                sb.Append("<tr bgcolor=\"#FFFFFF\" align=\"center\">");
                                sb.Append("<td width=\"10%\" align=\"center\">" + realName + "<input type=\"hidden\" name=\"Id\" value=\"" + item.tempId + "\" /></td>");
                                sb.Append("<td width=\"15%\" align=\"center\">" + dto.StartAddress + "</td>");
                                sb.Append("<td width=\"15%\" align=\"center\">" + dto.EndAddress + "</td>");
                                sb.Append("<td width=\"15%\" align=\"center\">" + dto.BusDate + "</td>");

                                sb.Append("<td width=\"10%\" align=\"center\">" + dto.Transport + "</td>");
                                sb.Append("<td width=\"10%\" align=\"center\">" + dto.Fee + "</td>");
                                sb.Append("<td width=\"10%\" align=\"center\">" + dto.InvoiceCount + "</td>");
                                sb.Append("<td width=\"5%\" align=\"center\"><button type=\"button\" onclick=\"removeInfo(" + item.tempId + ")\">[-]</button></td>");
                                sb.Append("</tr>");
                            }
                            j++;
                        }
                    }

                }
            }

            return sb.ToString() + "^" + days + "^" + totalfee + "^" + totalinvoicecount;
        }

        [HttpPost]
        public ActionResult SaveLongHaulFee(string selyearmonth, int state = 0, int MainId = 0,int projectId=0)
        {
            if (System.Web.HttpContext.Current.Request.Cookies["LongHaulDetail"] == null)
            {
            }
            else
            {
                HttpCookie oCookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["LongHaulDetail"];
                // oCookie.Expires = DateTime.Now.AddHours(1);
                string tempCart = System.Web.HttpUtility.UrlDecode(oCookie.Value, Encoding.GetEncoding("UTF-8")).ToString(); 
                var tempList = new List<LongHaulDetail>();
                tempList = TypePlug.ToObject<List<LongHaulDetail>>(tempCart);

                int days = 0;
                decimal totalfee = 0;
                int totalInvoice = 0;
                decimal totalallowance = 0;

                foreach (var item in tempList)
                {
                    days = days + item.Days;
                    totalfee = totalfee + item.TotalFee;
                    totalInvoice = totalInvoice + item.InvoiceCount;
                    // item.PostAdd();
                }
                totalallowance = days * SupportBiz.GetAllowanceMoney();
                var longfee = new LongHaul();
                if (MainId > 0)
                {
                     longfee = new LongHaul().Find(MainId.ToString());
                    if (selyearmonth != null && selyearmonth != "无")
                    {
                        string[] temp = selyearmonth.Split('$')[0].Split(':');
                        longfee.EndDate = temp[3];
                        longfee.Month = temp[1];
                        longfee.StartDate = temp[2];
                        longfee.Year = temp[0];
                    }
                    longfee.Status = state;
                    longfee.ProjectId = projectId;
                    longfee.TotalDays = days;
                    longfee.TotalFee = totalfee;
                    longfee.InvoiceCount = totalInvoice;
                    longfee.AllowanceMoney = totalallowance;
                    longfee.UserName = System.Web.HttpContext.Current.User.Identity.Name;

                    longfee.PostModify();
                    var detailList = new LongHaulDetail().FindAll(c => c.LongHaulId == longfee.Id);
                    foreach (var item in detailList)
                    {
                        var tempItem = new LongHaulDetail().Find(item.Id.ToString());
                        tempItem.PostDelete();
                    }
                }
                else
                {
                    longfee = new LongHaul();
                    if (selyearmonth != null && selyearmonth != "无")
                    {
                        string[] temp = selyearmonth.Split('$')[0].Split(':');
                        longfee.EndDate = temp[3];
                        longfee.Month = temp[1];
                        longfee.StartDate = temp[2];
                        longfee.Year = temp[0];
                    }
                    longfee.Status = state;
                    longfee.ProjectId = projectId;
                    longfee.TotalDays = days;
                    longfee.TotalFee = totalfee;
                    longfee.InvoiceCount = totalInvoice;
                    longfee.AllowanceMoney = totalallowance;
                    longfee.UserName = System.Web.HttpContext.Current.User.Identity.Name;
                    longfee = longfee.PostAdd();
                }
               
                foreach (var item in tempList)
                {
                    item.LongHaulId = longfee.Id;
                    item.PostAdd();
                }
                oCookie.Expires = DateTime.Now.AddDays(-1);
            }

            return Redirect("/Reimbursement/LongHaulFee");
        }
        public ActionResult ChangeLongHaulState(int page = 0, int Id = 0, int state = 0)
        {
            if (state == -1)//删除
            {
                var longHaulfee = new LongHaul().Find(Id.ToString());
                longHaulfee.PostDelete();
                var details = new LongHaulDetail().FindAll(c => c.LongHaulId == Id);
                foreach (var item in details)
                {
                    var tempItem = new LongHaulDetail().Find(item.Id.ToString());
                    tempItem.PostDelete();
                }
            }
            else
            {
                var longHaulfee = new LongHaul().Find(Id.ToString());
                longHaulfee.Status = state;
                longHaulfee.PostModify();
            }
            return Redirect("/Reimbursement/LongHaulFee?page=" + page);
        }
        #endregion
        #region 住宿费
        public ActionResult HotelFee(int page = 0)
        {
            ViewBag.feelist = HotelFeeBiz.GetAllHotelFee(page, 20);
            return View();
        }

        public ActionResult HotelFeeDetail(int Id = 0)
        {
            var yearmonth = new FinancialPeriod().FindAll();
            ViewBag.YearMonth = yearmonth;
            var user = new User().Find(c => c.UserName == System.Web.HttpContext.Current.User.Identity.Name);
            ViewBag.User = user;
            ViewBag.projects = new Project().FindAll();
            if (Id > 0)
            {
                using (Context ctx = new Context())
                {
                    var data = (from c in ctx.HotelFee
                                join d in ctx.Project
                                on c.ProjectId equals d.Id
                                where c.Id == Id
                                select new { c, d })
                              .ToList()
                              .Select(e => new HotelFee().Set(e.c).LoadProject(e.d)).FirstOrDefault();
                    var hotelFee = data;
                    ViewBag.hotelFee = hotelFee;
                }

               // var hotelFee = new HotelFee().Find(Id.ToString());
                var hotelFeeDetails = new HotelFeeDetail().FindAll(c => c.HotelId == Id);
               // ViewBag.hotelFee = hotelFee;
                ViewBag.hotelFeeDetails = hotelFeeDetails;
            }
            return View();
        }

        [HttpPost]
        public ActionResult SaveHotelFee(string[] CheckInDate, string[] CheckOutDate,
            string[] Days, string[] TravelAddress, string[] HotelName, string[] Price, string[] TotalFee, string[] invoicecount,
            string selyearmonth, int state = 0, int MainId = 0,int projectId=0)
        {

            if (CheckInDate != null && CheckInDate.Length > 0)
            {
                var fee = new HotelFee();
                var feeDetails = new List<HotelFeeDetail>();
                int dayCount = 0;
                decimal totalFee = 0;
                int invoiceCount = 0;
                for (int i = 0; i < CheckInDate.Length; i++)
                {
                    if (CheckInDate[i] != "" && CheckOutDate[i] != "")
                    {
                        var feeDetail = new HotelFeeDetail();
                        feeDetail.CheckInDate = CheckInDate[i];
                        feeDetail.CheckOutDate = CheckOutDate[i];
                        int day = (Convert.ToDateTime(CheckOutDate[i]) - Convert.ToDateTime(CheckInDate[i])).Days;
                        feeDetail.Days = day+1;
                        dayCount = dayCount + (day+1);
                        feeDetail.HotelName = HotelName[i];
                        int count = int.Parse(invoicecount[i] == "" ? "0" : invoicecount[i]);
                        invoiceCount = invoiceCount + count;
                        feeDetail.InvoiceCount = count;
                        decimal price = decimal.Parse(Price[i] == "" ? "0" : Price[i]);
                        feeDetail.Price = price;
                        feeDetail.TotalFee = price * day;
                        totalFee = totalFee + price * day;
                        feeDetail.TravelAddress = TravelAddress[i];
                        feeDetails.Add(feeDetail);
                    }

                }
                if (selyearmonth != null && selyearmonth != "无")
                {
                    string[] temp = selyearmonth.Split('$')[0].Split(':');
                    fee.EndDate = temp[3];
                    fee.Month = temp[1];
                    fee.StartDate = temp[2];
                    fee.Year = temp[0];
                }
                fee.Id = MainId;
                fee.ProjectId = projectId;
                fee.InvoiceCount = invoiceCount;
                fee.Status = state;
                fee.TotalDays = dayCount;
                fee.TotalFee = totalFee;
                fee.UserName = System.Web.HttpContext.Current.User.Identity.Name;
                if (MainId > 0)
                {
                    var details = new HotelFeeDetail().FindAll(c => c.HotelId == MainId);
                    foreach (var item in details)
                    {
                        var tempItem = new HotelFeeDetail().Find(item.Id.ToString());
                        tempItem.PostDelete();
                    }
                }

                HotelFeeBiz.SaveHotelFee(fee, feeDetails);
            }

            return Redirect("/Reimbursement/HotelFee");
        }

        public ActionResult ChangeHotelFeeState(int page = 0, int Id = 0, int state = 0)
        {
            if (state == -1)//删除
            {
                var hotelFee = new HotelFee().Find(Id.ToString());
                hotelFee.PostDelete();
                var details = new HotelFeeDetail().FindAll(c => c.HotelId == Id);
                foreach (var item in details)
                {
                    var tempItem = new HotelFeeDetail().Find(item.Id.ToString());
                    tempItem.PostDelete();
                }
            }
            else
            {
                var hotelFee = new HotelFee().Find(Id.ToString());
                hotelFee.Status = state;
                hotelFee.PostModify();
            }
            return Redirect("/Reimbursement/HotelFee?page=" + page);
        }
        #endregion

        #region 汇总
        public ActionResult GetAllSummary(int page=0)
        {
            string userName=System.Web.HttpContext.Current.User.Identity.Name;
            int count = 0;
            using (Context ctx = new Context())
            {
                string countSql = @"select  a.*,b.ProjectCode,b.ProjectName from 
                            (select Year,Month, ProjectId from dbo.T_CityTaxi where UserName=@username
                            union
                            select Year,Month, projectid from dbo.T_HotelFee  where UserName=@username
                            union
                            select Year,Month, projectid from dbo.T_LongHaul  where UserName=@username) a
                            inner join T_Project b on a.ProjectId=b.Id";
                var dataCount = ctx.ExcuteSQL(countSql,
                    new SqlParameter("@username", userName)
                    );
                count = dataCount != null ? dataCount.Rows.Count : 0;
            }

            using (Context ctx = new Context())
            {
                string sql = @"select top (@pagesize) t.* from (select ROW_NUMBER() OVER (ORDER BY a.year,a.month,projectid desc) AS RowNumber, a.*,b.ProjectCode,b.ProjectName from 
                            (select Year,Month,StartDate,EndDate, ProjectId from dbo.T_CityTaxi where UserName=@username
                            union
                            select Year,Month,StartDate,EndDate, projectid from dbo.T_HotelFee  where UserName=@username
                            union
                            select Year,Month,StartDate,EndDate, projectid from dbo.T_LongHaul  where UserName=@username) a
                            inner join T_Project b on a.ProjectId=b.Id) t
                            where  t.RowNumber>@pagesize*@page";
                var datatable = ctx.ExcuteSQL(sql,
                    new SqlParameter("@username", userName),
                         new SqlParameter("@pagesize", 20),
                     new SqlParameter("@page", page)
                    );
                List<MonthProjectDTO> monthProjectList = null;
                if (datatable != null && datatable.Rows.Count > 0)
                {
                    monthProjectList = new List<MonthProjectDTO>();
                    foreach (DataRow dr in datatable.Rows)
                    {
                        var monthProject = new MonthProjectDTO();
                        monthProject.Year = dr["Year"].ToString();
                        monthProject.Month = dr["Month"].ToString();
                        monthProject.StartDate = dr["StartDate"].ToString();
                        monthProject.EndDate = dr["EndDate"].ToString();
                        monthProject.ProjectId = dr["ProjectId"].ToString();
                        monthProject.ProjectCode = dr["ProjectCode"].ToString();
                        monthProject.ProjectName = dr["ProjectName"].ToString();
                        monthProjectList.Add(monthProject);
                    }
                   
                }

                var list = new ItemListBox<MonthProjectDTO>(monthProjectList).BuildPage(
                      count, page, 20, new PageParameter() { Style = "workspace" });
                ViewBag.monthProjects = list;    
            }
            return View();
        }

        public ActionResult GetSummaryDetail(string year, string month, int projectId = 0)
        {
            string username=System.Web.HttpContext.Current.User.Identity.Name;
            var taxiFee = new CityTaxi().Find(c => c.Year == year && c.Month == month && c.ProjectId == projectId&&c.UserName==username);
            var hotelFee = new HotelFee().Find(c => c.Year == year && c.Month == month && c.ProjectId == projectId&&c.UserName==username);
            var longFee = new LongHaul().Find(c => c.Year == year && c.Month == month && c.ProjectId == projectId&&c.UserName==username);
            var user = new User().Find(c => c.UserName == username);
            var project = new Project().Find(projectId.ToString());
            ViewBag.taxiFee = taxiFee;
            ViewBag.hotelFee = hotelFee;
            ViewBag.longFee = longFee;
            ViewBag.user = user;
            ViewBag.project = project;

            return View();
        }
        #endregion

    }
}
